package com.serkol.ams.controller.api;


import com.serkol.ams.bean.Result;
import com.serkol.annotation.IsLogin;
import com.serkol.config.Constract;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultConstant;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Hesenjan(Serkol)
 * @since 2021-11-17
 */

@RestController
@RequestMapping("api/cdn/sys/redis")
public class SysRedisController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${spring.redis.port}")
    private Integer port;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.database}")
    private Integer database;

    @IsLogin
    @GetMapping("findByList")
    public Result list() {


      //  Jedis jedis = new Jedis("127.0.0.1", 6379);
        Map<String, Object> map1 = new HashMap<>();


        map1.put("ip", host);
        map1.put("port", port);



        //    map1.put("time", jedis.);
        //   List<String> strings = jedis.aclUsers();
        List<Map<String, Object>> list = new ArrayList();

                Set<String> keys = redisTemplate.keys("*");
                if(map1.containsKey("count")){
                    Object count = map1.get("count");
                    Integer integer = NumberUtils.createInteger(count.toString());
                 int   integer1=integer.intValue()+keys.size();
                    map1.put("count",integer1);
                }else{
                    map1.put("count",keys.size());
                }

                System.out.println("COUNT" + keys.size());
                Iterator<String> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> map = new HashMap<>();
                    String next = iterator.next();
                    map.put("db",database);
                    map.put("key", next);
                    map.put("size", redisTemplate.opsForValue().get(next).toString().length());
                    list.add(map);
                }


        map1.put("list", list);
        return Result.ok(map1);
    }
    @IsLogin
    @ResponseBody
    @PostMapping(value = "/delAll")
    public Result delCache() {
        boolean state = false;
        Set<String> keys = redisTemplate.keys("*");
        for (String key : keys) {
            redisTemplate.delete(key);
            state = true;
        }
        if (state) {
            AuthConstant.setSettingsInfo(null);
            return Result.ok(ResultConstant.SUCSESS);
        } else {
            return Result.failure("无缓存数据可清除！");
        }
    }
}




